<script setup>
import { getProjectInfo } from '@/assets/api/project-info'
import { useDictionary } from '@/use/use-dictionary'
import { RefreshRight, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { riskColor, riskSeverityColor } from '@/utils/task-utils'
import { getUserList } from '@/assets/api/user'
import {
  getProjectRiskInfo,
  addProjectRisk,
  editProjectRisk,
  getProjectRiskSolution,
  delProjectRisk,
  enProjectRisk,
  riskTreatment,
  getRiskHandlingRecord,
} from '@/assets/api/project-risk'
import { getProjectMember } from '@/assets/api/project-member'

const dict = useDictionary(['task_risk_status', 'task_risk_category', 'task_risk_severity', 'task_risk_probability'])

const props = defineProps({
  projectId: {
    type: String,
    default: '',
  },
})

const userList = ref([])
function getUserListData() {
  getUserList().then((res) => {
    if (res.code === 200) {
      userList.value = res.rows || []
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 获取项目基本信息
const proBaseMsg = ref({})
const teamMember = ref([])
const getProBaseMsg = async () => {
  const r1 = await getProjectInfo(props.projectId)
  proBaseMsg.value = r1?.data || {}

  const r2 = await getProjectMember({ projectId: props.projectId, effectFlag: 1 })
  teamMember.value = r2?.rows || []
}
getProBaseMsg()

// 查询表单
class SearchForm {
  riskName = ''
  status = ''
}
const searchForm = ref(new SearchForm())
const handleSearch = () => {
  getTable()
}
const handleReset = () => {
  searchForm.value = new SearchForm()
  getTable()
}

// 获取项目风险列表
const tableData = ref([])
const getTable = () => {
  const params = {}
  for (const key in searchForm.value) {
    if (Object.hasOwnProperty.call(searchForm.value, key)) {
      const element = searchForm.value[key]
      if (element) {
        params[key] = element
      }
    }
  }

  getProjectRiskInfo({ ...params, projectId: props.projectId }).then((r) => {
    tableData.value = r.rows || []
  })
}
const translateName = (source) => {
  const temp = teamMember.value.find((item) => item.userId === source)
  return temp?.userName || ''
}
getTable()

//查询风险变更记录表
const getRiskHandlingRecordList = (riskId) => {
  getRiskHandlingRecord(riskId).then((r) => {
    solutionData.value = r.rows || []
  })
}

/**
 * 风险操作 - 新增 编辑
 */
class AddForm {
  riskId = ''
  riskType = ''
  riskName = ''
  severity = ''
  riskContent = ''
  status = ''
  probability = ''
  proposer = ''
  discoveryTime = ''
  confirmedBy = ''
  confirmedTime = ''
  solutions = ''
  projectId = props.projectId
}
const isShowAdd = ref(false)
const isFullScreen = ref(false)
const isSubmitLoading = ref(false)
const addTitle = ref('新增风险')
const addForm = ref(new AddForm())
const addFormRef = ref()
const handleAddOpen = () => {
  addTitle.value = '新增风险'
  ifSetting.value = false
  addForm.value = new AddForm()
  isShowAdd.value = true
}
const handleEditOpen = (row) => {
  addTitle.value = '编辑风险'
  ifSetting.value = false
  addForm.value = JSON.parse(JSON.stringify(row))
  isShowAdd.value = true
}
const handleAddClose = () => {
  isFullScreen.value = false
  addFormRef.value.addForm.resetFields()
  isShowAdd.value = false
  view.value = false
}
const view = ref(false)
const handleView = (row) => {
  addTitle.value = '查看风险'
  ifSetting.value = false
  addForm.value = JSON.parse(JSON.stringify(row))
  isShowAdd.value = true
  view.value = true
}

const handleAddSubmit = () => {
  const formRef = addFormRef.value.addForm
  formRef.validate(async (r) => {
    if (r) {
      const data = {}
      for (const key in addForm.value) {
        if (Object.hasOwnProperty.call(addForm.value, key)) {
          const element = addForm.value[key]
          data[key] = element
        }
      }

      try {
        if (addTitle.value === '新增风险') {
          await addProjectRisk(data)

          ElMessage({
            type: 'success',
            message: '新增成功',
          })
        } else {
          await editProjectRisk(data)
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
        }

        isShowAdd.value = false
        getTable()
      } catch (error) {
        console.log(error)
      }
    }
  })
}

/**
 * 风险操作 - 处理
 */
const ifSetting = ref(false)
const isShowSetting = ref(false)
const activities = ref({})
const settingFormRef = ref()
const solutionData = ref([
  {
    riskId: '',
    changedType: 0,
    hrId: '',
    changeData: '',
    createUser: '',
    createTime: '',
    updateUser: '',
    updateTime: '',
  },
])
const handleSetting = (row) => {
  addTitle.value = '新增风险'
  addForm.value = JSON.parse(JSON.stringify(row))

  getProjectRiskSolution(row.riskId).then((r) => {
    getRiskHandlingRecordList(row.riskId)
    getUserListData()
    activities.value = r.data
    ifSetting.value = true
    setTimeout(() => {
      isShowSetting.value = true
    }, 200)
  })
}
const handleSettingClose = () => {
  isFullScreen.value = false
  settingFormRef.value.addForm.resetFields()
  activities.value = {}
  isShowSetting.value = false
  view.value = false
}
/**
 * 风险操作 - 处理
 */
const handleSettingSubmit = () => {
  const formRef = settingFormRef.value.addForm
  formRef.validate((r) => {
    if (r) {
      riskTreatment(addForm.value).then((r) => {
        ElMessage({
          type: 'success',
          message: '处理成功',
        })
        isShowSetting.value = false
        getTable()
      })
    }
  })
}

/**
 * 风险操作 - 删除
 */
const handleDel = (row) => {
  ElMessageBox.confirm(`确定要删除风险【${row.riskName}】吗？`, '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      delProjectRisk(row.riskId).then((r) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getTable()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

/**
 * 风险操作 - 风险确认
 */
const handleAffirm = (row) => {
  ElMessageBox.confirm(`确定要确认风险【${row.riskName}】吗？`, '确认提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      enProjectRisk(row.riskId).then((r) => {
        ElMessage({
          type: 'success',
          message: '确认成功',
        })
        getTable()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
</script>

<template>
  <div class="risk-manage">
    <div class="risk-manage-header">
      <div class="risk-manage-header-title">{{ proBaseMsg.projectName }}</div>

      <el-form inline :model="searchForm" class="risk-manage-header-form" label-width="85px">
        <el-form-item label="风险名称">
          <el-input v-model="searchForm.riskName" placeholder="请输入风险名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="风险状态">
          <el-select v-model="searchForm.status" placeholder="请选择风险状态" style="width: 200px" clearable>
            <el-option
              v-for="(item, index) in dict.dictMap['task_risk_status']"
              :key="index"
              :label="item.dictLabel"
              :value="Number(item.dictValue)" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon class="risk-manage-header-form-icon"><Search /></el-icon>
            搜索
          </el-button>
          <el-button type="" @click="handleReset">
            <el-icon class="risk-manage-header-form-icon"><RefreshRight /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="handleAddOpen" class="risk-manage-header-btn">新增</el-button>
    </div>

    <div class="risk-manage-content">
      <el-table :data="tableData" stripe style="width: 100%" border max-height="70vh">
        <el-table-column prop="riskName" label="风险名称" width="180" />
        <el-table-column prop="riskType" label="风险类别" width="120">
          <template #default="scope">
            {{ dict.translate('task_risk_category', scope.row.riskType) }}
          </template>
        </el-table-column>
        <el-table-column prop="probability" label="发生概率" width="120">
          <template #default="scope">
            <div class="quality-tag" :style="riskColor(scope.row.probability)">
              {{ dict.translate('task_risk_probability', scope.row.probability) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="120">
          <template #default="scope">
            <div class="quality-tag" :style="riskSeverityColor(scope.row.severity)">
              {{ dict.translate('task_risk_severity', scope.row.severity) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="风险状态" width="90">
          <template #default="scope">
            {{ dict.translate('task_risk_status', scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="proposer" label="提出人" width="120">
          <template #default="scope">
            {{ translateName(scope.row.proposer) }}
          </template>
        </el-table-column>
        <el-table-column prop="discoveryTime" label="提出时间" show-overflow-tooltip />
        <el-table-column prop="confirmedBy" label="确认人" width="120">
          <template #default="scope">
            {{ translateName(scope.row.confirmedBy) }}
          </template>
        </el-table-column>
        <el-table-column prop="confirmedTime" label="确认时间" show-overflow-tooltip />
        <el-table-column prop="options" label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button v-if="row.status < 5" link type="primary" @click="handleEditOpen(row)">编辑</el-button>
            <el-button v-if="row.confirmedBy" link type="primary" @click="handleSetting(row)">处理</el-button>
            <el-button v-if="!row.confirmedBy && row.status < 5" link type="primary" @click="handleAffirm(row)">
              风险确认
            </el-button>
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <TaskChatDialog
      v-model="isShowAdd"
      :title="addTitle"
      bodyClassName="add-risk-dialog"
      width="80%"
      destroy-on-close
      append-to-body
      :fullscreen="isFullScreen"
      @close="handleAddClose">
      <ProjectRiseAddForm
        ref="addFormRef"
        :formData="addForm"
        :ifAdd="addTitle === '新增风险'"
        :projectId="projectId"
        :projectMemberList="teamMember"
        :view="view"
        @changeLoading="(val) => (isSubmitLoading = val)"
        @changeFullScreen="
          (val) => {
            isFullScreen = val
          }
        " />
      <template #footer>
        <el-button @click="handleAddClose">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit" :loading="isSubmitLoading">确定</el-button>
      </template>
    </TaskChatDialog>

    <TaskChatDialog
      v-model="isShowSetting"
      title="风险处理"
      bodyClassName="setting-risk-dialog"
      width="90%"
      destroy-on-close
      append-to-body
      :fullscreen="isFullScreen"
      @close="handleSettingClose">
      <div class="risk-manage-setting-page">
        <ProjectRiseAddForm
          ref="settingFormRef"
          class="risk-manage-setting-page-form"
          :formData="addForm"
          :ifAdd="addTitle === '新增风险'"
          :ifSetting="ifSetting"
          :projectId="projectId"
          :projectMemberList="teamMember"
          @changeLoading="(val) => (isSubmitLoading = val)"
          @changeFullScreen="
            (val) => {
              isFullScreen = val
            }
          " />
        <div class="risk-manage-setting-page-record">
          <div class="project-header">
            <div class="project-header-icon"></div>
            <div class="project-header-title">变更记录</div>
          </div>
          <!-- 时间轴 -->
          <ProjectRiseTimeLine :solutionData="solutionData" :projectMemberList="userList" />
        </div>
      </div>
      <template #footer>
        <el-button @click="handleSettingClose">取消</el-button>
        <el-button type="primary" @click="handleSettingSubmit" :loading="isSubmitLoading">确定</el-button>
      </template>
    </TaskChatDialog>
  </div>
</template>

<style scoped lang="scss">
.risk-manage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  &-title {
    font-size: 18px;
    font-weight: 700;
  }

  &-form-icon {
    margin-right: 5px;
  }

  :deep(.elp-form-item) {
    margin: 0;
    margin-right: 20px;
  }
}

.risk-manage-content {
  margin-top: 20px;
}

.risk-manage-setting-page {
  display: flex;
  max-height: calc(100vh - 240px);

  &-record {
    flex: 1;
    padding-left: 20px;
    padding-right: 10px;
    border-left: 1px solid #dcdfe6;
    overflow: auto;
  }

  &-form {
    flex: 2;
    padding-right: 10px;
    overflow: auto;
  }
}

.project-header {
  @include use-flex(center, flex-start);
  margin-bottom: 10px;
  &-icon {
    width: 3px;
    height: 16px;
    background: #005fff;
    border-radius: 1px;
    margin-right: 8px;
  }
  &-title {
    font-size: 16px;
    font-weight: 700;
    color: #2e3033;
    line-height: 24px;
  }
  &-button {
    margin-left: auto;
  }
}

.quality-tag {
  font-size: 12px;
  display: inline-block;
  padding: 2px 15px;
  border-radius: 50px;
  & + .quality-tag {
    margin-left: 5px;
  }
}

.pagination {
  margin-top: 20px;
}
.elp-pagination {
  justify-content: center;
}
</style>
